import { getDemandDetail, getDemandCommentsList, addDemandComment, updateIsFinishTrue, deleteDemand } from '../../../api/index'
import { formatTimeTwo, previewImg } from '../../../utils/util'
const app = getApp()

Page({
  data: {
    detailId: '',
    detail: {},
    currentPage: 1,
    pageSize: 15,
    commentList: [],
    safeBottom: 0,
    commentValue: '',
    showAllComment: false,
    currentItem: {},
    showCommentInput: false,
    userInfo: {},
    isEmpty: false,
    showHandles: false,
    actions: [
      {
        name: '删除',
        color: '#FF2E42',
        value: 'delete'
      }, {
        name: '取消',
        color: '#BBBBBB',
        value: 'cancel'
      }
    ]
  },
  settingDemand () {
    this.setData({ showHandles: true })
  },
  async selectHandle ({ detail }) {
    if (detail.value === 'edit') {
      this.setData({ showHandles: false })
      wx.$nav.navigateTo(`/pages/demand/edit/index?id=${this.data.detail.id}`)
    } else if (detail.value === 'setting') {
      this.setData({ showHandles: false })
      const { confirm } = await wx.$pro.showModal({ title: '提示', content: '确定要更改该需求状态吗？' })
      if (confirm) this.changeFinish()
    } else if (detail.value === 'delete') {
      this.setData({ showHandles: false })
      const { confirm } = await wx.$pro.showModal({ title: '提示', content: '确定要删除该需求吗？' })
      if (confirm) this.deleteDetail()
    } else {
      this.setData({ showHandles: false })
    }
  },
  async changeFinish () {
    try {
      await updateIsFinishTrue({ id: this.data.detail.id })
      wx.showToast({ title: '设置成功！', icon: 'none' })
      this.getDetail()
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async deleteDetail () {
    try {
      await deleteDemand({ id: this.data.detail.id })
      wx.showToast({ title: '删除成功！', icon: 'none' })
      wx.$nav.navigateBack()
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async sendComment ({ detail }) {
    try {
      let query = {
        materialFindPostId: this.data.detail.id,
        commentContext: detail
      }
      if (this.data.currentItem) {
        query.parentId = this.data.currentItem.id
        query.topId = this.data.currentItem.id
      }
      await addDemandComment({...query})
      wx.showToast({ title: '评论成功！', icon: 'none' })
      this.setData({
        showCommentInput: false,
        currentComment: null
      })
      this.getCommentList()
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  closeCommentModal () {
    this.setData({ showCommentInput: false })
    this.getCommentList()
  },
  replyComment ({ detail }) {
    this.setData({
      showCommentInput: true,
      currentItem: detail
    })
  },
  showAllCommentModal ({ currentTarget: { dataset: { item } } }) {
    this.setData({ showAllComment: true, currentItem: item })
    wx.setPageStyle({
      style: {
        overflow: 'hidden'
      }
    })
  },
  closeAllComment () {
    this.setData({ showAllComment: false, currentItem: null })
    wx.setPageStyle({
      style: {
        overflow: ''
      }
    })
  },
  changeInput ({ detail: { value } }) {
    this.setData({ commentValue: value })
  },
  async confirmComment () {
    try {
      await addDemandComment({ materialFindPostId: this.data.detailId, commentContext: this.data.commentValue })
      wx.showToast({ title: '评论成功！', icon: 'none' })
      this.setData({ commentValue: '' })
      this.getCommentList()
    } catch (err) {
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getDetail () {
    try {
      const { ResultSet } = await getDemandDetail({ id: this.data.detailId })
      ResultSet.userData.detail.createTime = formatTimeTwo(ResultSet.userData.detail.createTime, 'Y年M月D日')
      if (!ResultSet.userData.detail.isFinish) {
        if (ResultSet.userData.detail.reviewStatus === 2) {
          this.data.actions.unshift(...[{
            name: '设置为“已解决”',
            color: '#353535',
            value: 'setting'
          }])
        }
        if (ResultSet.userData.detail.reviewStatus === 1) {
          this.data.actions.unshift(...[{
            name: '编辑',
            color: '#353535',
            value: 'edit'
          }])
        }
      }
      this.setData({
        detail: ResultSet.userData.detail,
        actions: this.data.actions
      })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onReachBottom () {
    this.loadMore()
  },
  async loadMore () {
    try {
      if (this.loading || this.alloaded) return
      this.loading = true
      let query = {
        materialFindPostId: this.data.detailId,
        currentPage: this.data.currentPage,
        pageSize: this.data.pageSize
      }
      const { ResultSet } = await getDemandCommentsList({ ...query })
      this.alloaded = !ResultSet.userData.data.length
      this.data.isEmpty = !ResultSet.userData.data.length
      this.setData({ isEmpty: this.data.isEmpty })
      if (ResultSet.userData.data.length) {
        this.data.currentPage = this.data.currentPage + 1
        this.data.commentList.push(...ResultSet.userData.data)
        this.setData({
          commentList: this.data.commentList,
          currentPage: this.data.currentPage
        })
      }
      this.loading = false
    } catch (err) {
      this.loading = false
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors })
    }
  },
  async getCommentList () {
    try {
      const { ResultSet } = await getDemandCommentsList({ currentPage: 1, pageSize: this.data.pageSize, materialFindPostId: this.data.detailId })
      ResultSet.userData.data.forEach(item => {
        item.commentTime = formatTimeTwo(item.commentTime, 'Y-M-D')
        item.childCommentList.forEach(row => {
          row.commentTime = formatTimeTwo(item.commentTime, 'Y-M-D')
        })
      })
      this.data.isEmpty = ResultSet.userData.data.length && ResultSet.userData.data.length < this.data.pageSize
      this.setData({
        currentPage: 2,
        isEmpty: this.data.isEmpty,
        commentList: ResultSet.userData.data
      })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad ({ id }) {
    const { screenHeight, safeArea: { bottom } } = wx.$pro.getSystemInfoSync()
    const { userInfo } = app.globalData
    this.setData({ detailId: id, safeBottom: screenHeight - bottom, userInfo: userInfo })
  },
  onShow () {
    this.getDetail()
    this.getCommentList()
  }
})